package com.wuyou.designPatterns.adapter.questions;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;
import java.util.Set;

public class FileProperties implements FileIO {

    private final Properties properties;

    public FileProperties() {
        properties = new Properties();
    }

    public FileProperties(Properties defaults) {
        this.properties = defaults;
    }

    @Override
    public void readFromFile(String fileName) throws IOException {
        File file = new File(fileName);
        BufferedReader bis = new BufferedReader(new FileReader(file));

        String temp;
        while ((temp = bis.readLine()) != null) {
            if (!temp.startsWith("#")) {
                System.out.println(temp);
            }
        }
    }

    @Override
    public void writeToTile(String fileName) throws IOException {
        File file = new File(fileName);
        StringBuilder sb = new StringBuilder();
        sb.append("#Written By FileProperties")
                .append("\n")
                .append("#")
                .append(DateUtil.now())
                .append("\n");
        if(file.exists()){
            file.deleteOnExit();
        }
        Set<Object> keys = this.properties.keySet();
        for (Object key : keys) {
            sb.append(key).append("=").append(this.properties.get(key)).append("\r");
        }
        byte[] data = sb.toString().getBytes();
        OutputStream os = Files.newOutputStream(file.toPath());
        byte[] buffer = new byte[1024];
        int len = 0;
        while (len < data.length) {
            os.write(data, len, Math.min(data.length - 1, buffer.length));
            len +=data.length;
        }
    }

    @Override
    public void setValue(String key, String value) {
        this.properties.setProperty(key, value);
    }

    @Override
    public String getValue(String key) {
        return (String) this.properties.get(key);
    }
}
